package cn.wolfcode.edu.filter;

import cn.wolfcode.edu.util.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;

public class ExtendFormAuthenticationFilter extends FormAuthenticationFilter {
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("text/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        //登陆成功 响应jsonResult
        JsonResult jsonResult = new JsonResult();
        //转换类型
        String s = new ObjectMapper().writeValueAsString(jsonResult);
        PrintWriter writer = response.getWriter();
        writer.print(s);
        writer.flush();
        writer.close();
        return false;
    }

    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        this.setFailureAttribute(request, e);
        JsonResult jsonResult = new JsonResult();
        response.setContentType("text/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String name = e.getClass().getSimpleName();
        if (name.equals("IncorrectCredentialsException")) {
            jsonResult = jsonResult.remark("密码错误");
        } else if (name.equals("UnknownAccountException")) {
            jsonResult = jsonResult.remark("该用户不存在");
        } else {
            jsonResult = jsonResult.remark("其他异常");
        }
        String jsonString = null;
        try {
            jsonString = new ObjectMapper().writeValueAsString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.print(jsonString);
            writer.flush();
            writer.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return false;
    }
}
